import type { App } from 'vue'
import { useUserStoreHook } from '@/store/modules/user'
export interface UserInfo<T = number> {
  id: T
  name: string
  nickname: null | string
  phone: null | string
  roleName?: string
  roleCode?: string
  roleId?: number
  avatar?: null | string
  email?: null | string
  createTime: string
  updateTime: string
  description?: null | string
  password?: null | string
}

export interface UserAuthItem {
  component: string
  description: null | string
  icon: null | string
  menuId: number
  name: string
  zhName: string
  operations: string
  parentId: null | number
  path: string
  roleId: number
  children?: Array<UserAuthItem>
}

/**
 * @description 按钮权限自定义指令
 */
const defineDirective = (app: App) => {
  app.directive('btn-auth', {
    mounted(el: HTMLImageElement, { value }) {
      if (!hasBtnAuth(value)) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  })
}

export const hasBtnAuth = (value: string): boolean => {
  const UserStore = useUserStoreHook()
  if (UserStore.userInfo.roleCode === 'Administrator') return true
  // 检查 value 是否包含 ':'
  if (!value.includes(':')) {
    console.error(
      `Invalid format for value: ${value}. Expected format: 'name:operation'`
    )
    return false
  }

  const [name, operation] = value.split(':')

  // 检查 name 是否存在于 operationAuth 中
  if (!UserStore.operationAuth.has(name)) {
    // console.warn(`Name not found in operationAuth: ${name}`)
    return false
  }

  // 获取操作集合
  const operations = UserStore.operationAuth.get(name)

  // 检查 operations 是否为 Set 对象
  if (!(operations instanceof Set)) {
    console.warn(
      `Expected a Set for operationAuth[${name}], but got: ${typeof operations}`
    )
    return false
  }

  // 检查 operation 是否存在于 operations 中
  return operations.has(operation)
}

export default {
  install(app: App) {
    defineDirective(app)
  }
}
